import json

from flask import Flask, request
from geventwebsocket.websocket import WebSocket
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer

app = Flask(__name__)

socket_dict = {}

@app.route("/app/<user_id>")
def ws_app(user_id):
	user_socket = request.environ.get("wsgi.websocket") #type:WebSocket
	if user_socket:
		socket_dict[user_id] = user_socket
	print(len(socket_dict),socket_dict)
	while 1:
		user_msg = user_socket.receive()
		msg_dict = json.loads(user_msg)
		usocket = socket_dict.get(msg_dict.get("to_user"))
		usocket.send(user_msg)

@app.route("/toy/<toy_id>")
def ws_toy(toy_id):
	user_socket = request.environ.get("wsgi.websocket") #type:WebSocket
	if user_socket:
		socket_dict[toy_id] = user_socket
	print(len(socket_dict), socket_dict)
	while 1:
		user_msg = user_socket.receive()
		msg_dict = json.loads(user_msg)
		usocket = socket_dict.get(msg_dict.get("to_user"))
		usocket.send(user_msg)


if __name__ == '__main__':
	serv = WSGIServer(("0.0.0.0", 9528), app, handler_class=WebSocketHandler)
	serv.serve_forever()
